<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票量化交易系统 - 仪表板</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        h1, h2, h3 {
            color: #333;
        }
        
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        
        button:hover {
            background-color: #0056b3;
        }
        
        input, select {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        
        th {
            background-color: #f8f9fa;
        }
        
        .success {
            color: green;
        }
        
        .error {
            color: red;
        }
        
        .hidden {
            display: none;
        }
        
        .stock-up {
            color: red;
        }
        
        .stock-down {
            color: green;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin: 20px 0;
        }
        
        .portfolio-summary {
            display: flex;
            justify-content: space-around;
            margin: 20px 0;
        }
        
        .summary-card {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            flex: 1;
            margin: 0 10px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>股票量化交易系统</h1>
        <div>
            <span id="user-name">用户</span>
            <button onclick="logout()">退出登录</button>
        </div>
    </div>
    
    <!-- 投资组合概览 -->
    <div class="container">
        <h2>投资组合概览</h2>
        <div class="portfolio-summary">
            <div class="summary-card">
                <h3>总资产</h3>
                <p id="total-assets">¥100,000.00</p>
            </div>
            <div class="summary-card">
                <h3>总收益</h3>
                <p id="total-profit" class="stock-up">¥5,000.00 (+5.00%)</p>
            </div>
            <div class="summary-card">
                <h3>持仓股票</h3>
                <p id="holding-stocks">5</p>
            </div>
        </div>
    </div>
    
    <!-- 股票数据区域 -->
    <div class="container">
        <h2>股票数据</h2>
        <div>
            <input type="text" id="stock-symbol" placeholder="股票代码 (如: 000001)">
            <button onclick="getRealStockData()">获取实时数据</button>
            <button onclick="getAllStocks()">获取所有股票</button>
            <button onclick="simulatePriceChanges()">模拟价格变动</button>
        </div>
        <div id="stock-data"></div>
        <div class="chart-container">
            <canvas id="priceChart"></canvas>
        </div>
    </div>
    
    <!-- 交易区域 -->
    <div class="container">
        <h2>交易操作</h2>
        <div>
            <select id="trade-type">
                <option value="BUY">买入</option>
                <option value="SELL">卖出</option>
            </select>
            <input type="text" id="trade-symbol" placeholder="股票代码">
            <input type="number" id="trade-quantity" placeholder="数量">
            <input type="number" id="trade-price" placeholder="价格">
            <button onclick="executeTrade()">执行交易</button>
        </div>
        <div id="trade-message"></div>
    </div>
    
    <!-- 策略区域 -->
    <div class="container">
        <h2>量化策略</h2>
        <div>
            <button onclick="getStrategies()">获取我的策略</button>
            <button onclick="createNewStrategy()">创建新策略</button>
        </div>
        <div>
            <h3>执行移动平均线策略</h3>
            <input type="text" id="ma-symbol" placeholder="股票代码">
            <input type="number" id="ma-short" placeholder="短期周期" value="5">
            <input type="number" id="ma-long" placeholder="长期周期" value="20">
            <button onclick="executeMAStrategy()">执行策略</button>
        </div>
        <div>
            <h3>执行RSI策略</h3>
            <input type="text" id="rsi-symbol" placeholder="股票代码">
            <input type="number" id="rsi-period" placeholder="周期" value="14">
            <input type="number" id="rsi-overbought" placeholder="超买阈值" value="70">
            <input type="number" id="rsi-oversold" placeholder="超卖阈值" value="30">
            <button onclick="executeRSIStrategy()">执行策略</button>
        </div>

         <div>
            <h3>布林带策略</h3>
            <input type="text" id="bb-symbol" placeholder="股票代码">
            <input type="number" id="bb-period" placeholder="天数" value="20">
            <input type="number" id="bb-multiplier" placeholder="倍数" value="2">
            <button onclick="executeBollingerBandsStrategy()">执行策略</button>
        </div>
        <div id="strategy-data"></div>
    </div>

    <script>
        // 获取基础路径
        const basePath = '/stock';
        
        // 全局变量
        let authToken = localStorage.getItem('authToken');
        let currentUser = null;
        let priceChart = null;
        
        // 页面加载时初始化
        window.onload = function() {
            initializeChart();
            updatePortfolioSummary();
        };
        
        // 初始化图表
        function initializeChart() {
            const ctx = document.getElementById('priceChart').getContext('2d');
            priceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '股票价格',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false
                        }
                    }
                }
            });
        }
        
        // 更新图表数据
        function updateChart(labels, data) {
            priceChart.data.labels = labels;
            priceChart.data.datasets[0].data = data;
            priceChart.update();
        }
        
        // 更新投资组合概览
        function updatePortfolioSummary() {
            // 模拟数据
            document.getElementById('total-assets').textContent = '¥105,000.00';
            document.getElementById('total-profit').textContent = '¥5,000.00 (+5.00%)';
            document.getElementById('holding-stocks').textContent = '5';
        }
        
        // 用户退出
        function logout() {
            authToken = null;
            currentUser = null;
            localStorage.removeItem('authToken');
            window.location.href = basePath + '/';
        }
        
        // 获取实时股票数据
        function getRealStockData() {
            const symbol = document.getElementById('stock-symbol').value;
            if (!symbol) {
                alert('请输入股票代码');
                return;
            }
            
            fetch(basePath + `/api/stocks/real/${symbol}`)
            .then(response => response.json())
            .then(data => {
                const stockDataDiv = document.getElementById('stock-data');
                if (data.success) {
                    const stock = data.data;
                    const changeClass = stock.change >= 0 ? 'stock-up' : 'stock-down';
                    stockDataDiv.innerHTML = `
                        <h3>${stock.name} (${stock.symbol})</h3>
                        <p>当前价格: <span class="${changeClass}">${stock.price}</span></p>
                        <p>涨跌额: <span class="${changeClass}">${stock.change}</span></p>
                        <p>涨跌幅: <span class="${changeClass}">${stock.changePercent}%</span></p>
                        <p>开盘价: ${stock.open}</p>
                        <p>最高价: ${stock.high}</p>
                        <p>最低价: ${stock.low}</p>
                        <p>成交量: ${stock.volume}</p>
                    `;
                    
                    // 更新图表（模拟数据）
                    const labels = [];
                    const prices = [];
                    for (let i = 0; i < 10; i++) {
                        labels.push(`时间${i+1}`);
                        prices.push(stock.price + (Math.random() - 0.5) * 2);
                    }
                    updateChart(labels, prices);
                } else {
                    stockDataDiv.innerHTML = `<p class="error">获取数据失败: ${data.error}</p>`;
                }
            })
            .catch(error => {
                document.getElementById('stock-data').innerHTML = `<p class="error">获取数据失败: ${error.message}</p>`;
            });
        }
        
        // 获取所有股票
        function getAllStocks() {
            fetch(basePath + '/api/stocks')
            .then(response => response.json())
            .then(data => {
                const stockDataDiv = document.getElementById('stock-data');
                if (data.success) {
                    let tableHtml = `
                        <table>
                            <thead>
                                <tr>
                                    <th>代码</th>
                                    <th>名称</th>
                                    <th>当前价格</th>
                                    <th>涨跌幅</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    
                    data.data.forEach(stock => {
                        const change = stock.priceChangePercentage || 0;
                        const changeClass = change >= 0 ? 'stock-up' : 'stock-down';
                        tableHtml += `
                            <tr>
                                <td>${stock.symbol}</td>
                                <td>${stock.name}</td>
                                <td>${stock.currentPrice}</td>
                                <td class="${changeClass}">${change.toFixed(2)}%</td>
                                <td>
                                    <button onclick="selectStock('${stock.symbol}')">选择</button>
                                </td>
                            </tr>
                        `;
                    });
                    
                    tableHtml += `
                            </tbody>
                        </table>
                    `;
                    
                    stockDataDiv.innerHTML = tableHtml;
                } else {
                    stockDataDiv.innerHTML = `<p class="error">获取数据失败: ${data.error}</p>`;
                }
            })
            .catch(error => {
                document.getElementById('stock-data').innerHTML = `<p class="error">获取数据失败: ${error.message}</p>`;
            });
        }
        
        // 选择股票
        function selectStock(symbol) {
            document.getElementById('stock-symbol').value = symbol;
            document.getElementById('trade-symbol').value = symbol;
            getRealStockData();
        }
        
        // 模拟价格变动
        function simulatePriceChanges() {
            fetch(basePath + '/api/stocks/simulate', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('价格变动模拟完成');
                    getAllStocks(); // 刷新股票列表
                } else {
                    alert(`模拟失败: ${data.error}`);
                }
            })
            .catch(error => {
                alert(`模拟失败: ${error.message}`);
            });
        }
        
        // 执行交易
        function executeTrade() {
            const type = document.getElementById('trade-type').value;
            const symbol = document.getElementById('trade-symbol').value;
            const quantity = document.getElementById('trade-quantity').value;
            const price = document.getElementById('trade-price').value;
            
            if (!symbol || !quantity || !price) {
                alert('请填写完整的交易信息');
                return;
            }
            
            // 简化实现，实际应该调用API创建和执行交易
            document.getElementById('trade-message').innerHTML = `
                <p class="success">交易执行成功！</p>
                <p>类型: ${type}, 股票: ${symbol}, 数量: ${quantity}, 价格: ${price}</p>
            `;
            
            // 更新投资组合概览
            updatePortfolioSummary();
        }
        
        // 获取策略
        function getStrategies() {
            // 简化实现，实际应该调用API获取策略
            document.getElementById('strategy-data').innerHTML = `
                <h3>我的策略</h3>
                <ul>
                    <li>移动平均线策略 - 激活</li>
                    <li>RSI策略 - 激活</li>
                </ul>
            `;
        }
        
        // 创建新策略
        function createNewStrategy() {
            const name = prompt('请输入策略名称:');
            if (name) {
                alert(`策略 "${name}" 创建成功`);
                getStrategies(); // 刷新策略列表
            }
        }
        
        // 执行移动平均线策略
        function executeMAStrategy() {
            const symbol = document.getElementById('ma-symbol').value;
            const shortPeriod = document.getElementById('ma-short').value;
            const longPeriod = document.getElementById('ma-long').value;
            
            if (!symbol) {
                alert('请输入股票代码');
                return;
            }
            
            // 简化实现，实际应该调用API执行策略
            document.getElementById('strategy-data').innerHTML = `
                <h3>移动平均线策略结果</h3>
                <p>股票: ${symbol}</p>
                <p>短期均线(${shortPeriod}): 100.5</p>
                <p>长期均线(${longPeriod}): 99.8</p>
                <p>信号: <span class="stock-up">买入</span></p>
            `;
        }
        
        // 执行RSI策略
        function executeRSIStrategy() {
            const symbol = document.getElementById('rsi-symbol').value;
            const period = document.getElementById('rsi-period').value;
            const overbought = document.getElementById('rsi-overbought').value;
            const oversold = document.getElementById('rsi-oversold').value;
            
            if (!symbol) {
                alert('请输入股票代码');
                return;
            }
            
            // 简化实现，实际应该调用API执行策略
            document.getElementById('strategy-data').innerHTML = `
                <h3>RSI策略结果</h3>
                <p>股票: ${symbol}</p>
                <p>RSI(${period}): 65</p>
                <p>信号: <span class="stock-up">持有</span></p>
            `;
        }
        function executeBollingerBandsStrategy(){
            const symbol = document.getElementById('bb-symbol').value;
            const period = document.getElementById('bb-period').value;
            const multiplier = document.getElementById('bb-multiplier').value;
            if (!symbol) {
                alert('请输入股票代码');
                return;
            }
        }
    </script>
</body>
</html>